<template>
  <div class="update-name-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="nav-bar-bg"
      title="设置昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('closeNameProup')"
      @click-right="onClickRight"
    />

    <!-- 输入框 -->
    <div class="field-wrap">
      <van-field
        v-model.trim="userNameClone"
        rows="5"
        autosize
        type="textarea"
        maxlength="50"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfileAPI } from '../../../api/index.js'
export default {
  name: 'updateGender',
  model: {
    prop: 'userName',
    event: 'update-name'
  },
  props: {
    userName: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      userNameClone: this.userName
    }
  },
  methods: {
    // 完成 - 自己写的
    // async onClickRight () {
    //   try {
    //     if (this.userNameClone.trim().length === 0) {
    //       this.$toast('昵称不能为空')
    //       return
    //     }
    //     await updateUserProfileAPI({
    //       name: this.userNameClone
    //     })
    //     this.$toast('修改昵称成功')
    //     // 关闭弹出层
    //     this.$emit('closeNameProup', true)
    //   } catch (error) {
    //     console.log(error)
    //     this.$toast('修改昵称失败')
    //   }
    // },
    // 老师讲的
    async onClickRight () {
      this.$toast.loading({
        duration: 0, // 持续展示加载状态弹框的毫秒数,当设置为0时,表示持续加载,需要主动关闭
        message: '加载中...',
        forbidClick: true // 是否禁用背景点击
      })
      try {
        if (this.userNameClone.trim().length === 0) {
          this.$toast('昵称不能为空')
          return
        }
        await updateUserProfileAPI({
          name: this.userNameClone
        })
        // 更新视图数据
        this.$emit('update-name', this.userNameClone)
        // 清空
        this.userNameClone = ''
        // 关闭弹出层
        this.$emit('closeNameProup')
        // 提示成功
        this.$toast.success('修改昵称成功')
      } catch (error) {
        console.log(error)
        if (error.response && error.response.status === 409) {
          this.$toast.fail('用户名已存在')
        } else {
          this.$toast.fail('修改昵称失败')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.update-name-container{
  .nav-bar-bg{
    background-color: #fff;
    :deep(.van-nav-bar__title){
      color: #000;
      font-size: 40px;
    }
  }
  .field-wrap {
    padding: 20px;
  }
}
</style>
